<template>
  <!-- <div @click="getCameras">打开扫一扫</div> -->
  <!-- <div style="height: 50rpx" @click="speak">播报</div> -->
  <topNav
    title="扫描模式"
    @save="saveFun"
    rType="code"
    @orcode="orFun"
  ></topNav>
  <div class="container" v-show="isShow">
    <div id="reader"></div>
  </div>
</template>

<script setup>
import topNav from "../components/topNav.vue";
import { reactive, onMounted, onUnmounted, ref, nextTick } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
// import { showToast  } from 'vant';
import { Html5Qrcode } from "html5-qrcode";
import Speech from "speak-tts"; //引入语音播报
import TrPlayer from "./TrPlayer";
import { useCodeStore } from "@/stores/code.js";
import { appPayCreate } from "@/services/cashier";
const codeStore = useCodeStore();
let html5QrCode = ref(null);
const isShow = ref(true);
const devicesInfo = ref(false);
const orderid = ref("");
const payNum = ref(0);
const payPrice = ref(0);

onMounted(() => {
  speechInit();
  nextTick(() => {
    getCameras();
  });

  setTimeout(() => {
    // trPlayer.play("120.5");
  }, 10000);
});

const orFun = () => {
  console.log("orcode");
};

const type = ref("");
onLoad((e) => {
  type.value = e.type;
  orderid.value = e.orderid ? e.orderid : "";
  payNum.value = e.payNum ? e.payNum : 0;
  payPrice.value = e.payPrice ? e.payPrice : 0;
});

const onSearchOrder = () => {
  console.log("在运运单");
  router.push("order");
};
const speak = () => {
  console.log("开始播报", speech.value);
  speech.value
    .speak({
      text: "山东发斯蒂芬阿斯蒂芬阿斯蒂芬啥打法阿斯蒂芬阿斯,蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬",
    })
    .then(() => {
      speech.value.cancel(); //播放结束后调用
    })
    .catch((e) => {
      alert(e);
      console.log(e);
    });

  return;
  if ("speechSynthesis" in window) {
    console.log("Web Speech API supported.");
    const msg = new SpeechSynthesisUtterance("你好，世界！¥1200014湿哒哒");
    msg.lang = "zh-CN"; // 设置语言为中文
    msg.rate = 1; // 设置语速，0.1 到 10 之间
    msg.pitch = 1; // 设置音高，0 到 2 之间
    msg.volume = 1; // 设置音量，0 到 1 之间
    window.speechSynthesis.speak(msg); // 开始播报
  } else {
    alert("Web Speech API not supported.");
  }
};

onUnmounted(() => {
  stop();
});

const codeTrue = ref(false);
const isPayTo = ref(false);

onShow(() => {
  codeTrue.value = false;
  isPayTo.value = false;
});

const speech = ref(null);

const speech2 = new Speech();
if (speech2.hasBrowserSupport()) {
  // 检测浏览器是否支持，returns a boolean
  console.log("语音引擎加载成功");
}

const speechInit = () => {
  speech.value = new Speech();
  speech.value.setLanguage("zh-CN");
  speech.value.init().then(() => {
    console.log("语音播报初始化完成");
  });
};

setTimeout(() => {
  console.log("开始播报");
  console.log("开始播报", speech.value);
  speech.value
    .speak({
      text: "山东发斯蒂芬阿斯蒂芬阿斯蒂芬啥打法阿斯蒂芬阿斯,蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬阿斯蒂芬",
    })
    .then(() => {
      speech.value.cancel(); //播放结束后调用
    })
    .catch((e) => {
      console.log(e);
    });
}, 5000);

const getCameras = () => {
  Html5Qrcode.getCameras()
    .then((devices) => {
      if (devices && devices.length) {
        html5QrCode = new Html5Qrcode("reader");
        // start开始扫描
        start();
      }
    })
    .catch((err) => {
      console.log("获取设备信息失败", err); // 获取设备信息失败
      // showToast('获取设备信息失败')
      uni.navigateBack();
      uni.showToast({
        title: "获取设备信息失败",
        icon: "none",
      });
    });
};

const start = () => {
  stop();
  html5QrCode
    .start(
      { facingMode: "environment" },
      {
        fps: 100, // 设置每秒多少帧
        qrbox: { width: 250, height: 250 }, // 设置取景范围
        // scannable, rest shaded.
      },
      async (decodedText, decodedResult) => {
        if (codeTrue.value) {
          return;
        }
        if (type.value == "payPrice") {
          if (isPayTo.value) {
            return;
          }
          isPayTo.value = true;

          try {
            let res = await appPayCreate({
              id: orderid.value,
              attach: "scan_pay",
              authCode: decodedText,
            });
            if (res.code == 200) {
              uni.redirectTo({
                url:
                  "/pages/cashier/paystate/index?orderid=" +
                  res.data.id +
                  "&payNum=" +
                  payNum.value,
              });
            } else {
              uni.showToast({
                title: res.msg,
                icon: "none",
              });
              uni.redirectTo({
                url:
                  "/pages/cashier/paystate/index?orderid=" +
                  res.data.id +
                  "&payNum=" +
                  payNum.value,
              });
            }
          } catch (e) {
            uni.showToast({
              title: e.msg,
              icon: "none",
            });
            uni.navigateBack();
          }

          return;
        }

        if (type.value == "addBarCode") {
          uni.setStorageSync("barCode", decodedText);
          // #ifdef H5
          history.back();

          // #endif
          // #ifndef H5
          uni.navigateBack();
          // #endif
        }
        if (type.value == "transfer") {
          showToast("扫码成功" + decodedText);
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/transfer/goods_search/index?code=" + decodedText,
            });
          }, 1000);
          return;
        }

        if (type.value == "price") {
          showToast("扫码成功" + decodedText);
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/goods/goods_price_search/index?code=" + decodedText,
            });
          }, 1000);
          return;
        }
        if (type.value == "goods") {
          showToast("扫码成功" + decodedText);
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/goods/goods_search/index?code=" + decodedText,
            });
          }, 1000);
          return;
        }
        devicesInfo.value = true;
        codeStore.setcode(decodedText);

        codeTrue.value = true;
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
      (errorMessage) => {
        // parse error, ideally ignore it. For example:
        // console.log(`QR Code no longer in front of camera.`);
        devicesInfo.value = true;
        console.log("暂无额扫描结果", errorMessage);
      }
    )
    .catch((err) => {
      // Start failed, handle it. For example,
      console.log(`Unable to start scanning, error: ${err}`);
    });
};
const hstart = () => {
  stop();
  html5QrCode
    .start(
      { facingMode: "user" },
      {
        fps: 20, // 设置每秒多少帧
        qrbox: { width: 250, height: 250 }, // 设置取景范围
        // scannable, rest shaded.
      },
      (decodedText, decodedResult) => {
        devicesInfo.value = true;

        // uni.navigateBack();
        alert("扫码结果" + decodedText);
      },
      (errorMessage) => {
        // parse error, ideally ignore it. For example:
        // console.log(`QR Code no longer in front of camera.`);
        devicesInfo.value = true;
        console.log("暂无额扫描结果", errorMessage);
      }
    )
    .catch((err) => {
      // Start failed, handle it. For example,
      console.log(`Unable to start scanning, error: ${err}`);
    });
};
const stop = () => {
  if (devicesInfo.value) {
    html5QrCode
      .stop()
      .then((ignore) => {
        // QR Code scanning is stopped.
        console.log("QR Code scanning stopped.", ignore);
      })
      .catch((err) => {
        // Stop failed, handle it.
        console.log("Unable to stop scanning.", err);
      });
  }
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  top: 0px;
  left: 0px;
  height: calc(100vh - 88rpx);
  width: 100%;
  background: rgba($color: #000000, $alpha: 0.48);
  // z-index: 999;
}
#reader {
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}
</style>
